package com.github.tomakehurst.wiremock.db.service.impl;

import com.github.tomakehurst.wiremock.db.entity.WireMockJournal;
import com.github.tomakehurst.wiremock.db.entity.WireMockJournalDetails;
import com.github.tomakehurst.wiremock.db.mapper.WireMockJournalMapper;
import com.github.tomakehurst.wiremock.db.service.JournalService;
import com.github.tomakehurst.wiremock.db.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class JournalServiceImpl implements JournalService {
    // 1. 初始化日志对象（传入当前类的 Class，便于定位日志来源）
    private static final Logger logger = LoggerFactory.getLogger(JournalServiceImpl.class);

    @Override
    public void saveJournal(WireMockJournal journal, WireMockJournalDetails details) {
        try (SqlSession session = MyBatisUtil.getSqlSession()) {
            WireMockJournalMapper mapper = session.getMapper(WireMockJournalMapper.class);

            // 2. 记录 INFO 级日志：保存前的关键信息
            logger.info("开始保存请求日志，日志ID：{}，请求URL：{}", journal.getId(), journal.getUrl());
            mapper.insertJournal(journal);
            mapper.insertJournalDetails(details);
            session.commit();
            // 3. 记录成功日志
            logger.info("请求日志保存成功，日志ID：{}，关联详情表ID：{}", journal.getId(), details.getJournalId());
        } catch (Exception e) {
            // 4. 记录错误日志（包含异常堆栈，便于排查）
            logger.error("保存请求日志失败，日志ID：{}，错误原因：", journal.getId(), e);
            throw e;
        }
    }

    @Override
    public WireMockJournal getJournalWithDetails(String id) {
        try (SqlSession session = MyBatisUtil.getSqlSession()) {
            WireMockJournalMapper mapper = session.getMapper(WireMockJournalMapper.class);
            return mapper.selectJournalWithDetails(id);
        }
    }

    @Override
    public List<WireMockJournal> listAllJournals() {
        try (SqlSession session = MyBatisUtil.getSqlSession()) {
            WireMockJournalMapper mapper = session.getMapper(WireMockJournalMapper.class);
            return mapper.selectAllJournals();
        }
    }
}